package com.rem.shiro.filter;

import com.rem.shiro.config.MyContext;
import com.rem.shiro.pojo.User;
import com.rem.shiro.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Rem
 * @date 2021-04-16
 */
@Component
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        String token = request.getHeader("token");
        //获取header中的token信息
        response.setCharacterEncoding("utf-8");


        //tooken为空
        if (StringUtils.isNotBlank(token)) {


            Claims claims = JwtUtils.getTokenInfo(token);

            String subject = claims.getSubject();
            String id = claims.getId();
            String username = (String) claims.get("username");
            Integer userId = (Integer) claims.get("userId");
            System.err.println("subject:" + subject);
            System.err.println("id:" + id);
            System.err.println("username:" + username);
            System.err.println("userId:" + userId);


            User user = new User();
            user.setId(userId).setUsername(username);

            new MyContext(user);
            chain.doFilter(request, response);
            return;
        }


        chain.doFilter(request, response);
    }
}
